Python reduce函数作用及实例代码解析

您所在的位置:网站首页 python isprime函数 Python reduce函数作用及实例代码解析

Python reduce函数作用及实例代码解析

#Python reduce函数作用及实例代码解析| 来源: 网络整理| 查看: 265

本篇文章小编给大家分享一下Python reduce函数作用及实例代码解析,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

语法

在python3中,内置函数中已经没有reduce了。要使用reduce,需要从functools模块里引入

可以看到,reduce有三个参数,第一个是函数function,第二个是序列sequence,第三个是initial,为初始值,默认为None

作用

对序列中的元素进行累积

返回值

返回函数的计算结果

代码实例

from functools import reduce from functools import reduce def add(x, y): return x + y print(reduce(add, [1, 2, 3, 4, 5])) #计算过程 ((((1 + 2) + 3) + 4) + 5) # 运行结果 15

在reduce中使用lambda函数

from functools import reduce print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])) # 运行结果 15

有初始值的情况,初始值为6

from functools import reduce print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 6)) # 运行结果 21 #计算过程 6 + 1 = 7 7 + 2 = 9 9 + 3 = 12 12 + 4 = 16 16+ 5 = 21


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3